import pandas as pd
from myback.models import *
import re
import os
import datetime
from utils.process_manager import process_manager


class ProcessOperator:
    """
    进程操作类
    """

    def __init__(self):
        # 获取ip地址
        ipstr = os.popen(""" ifconfig | sed -n "2p" """).readlines()[0]
        self.ip_address = re.findall("((?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d]))", ipstr)[0]

    def start_process(self, stg_id):
        try:
            # 生成进程对象
            process_stg = process_manager()
            # 进程管理器
            process_stg.get_current_process()

            ## 读取需要启停的程序
            rs_dict = \
                list(TBackapproval.objects.using("BackTestDB").values("runpath", "status").filter(envid="1",
                                                                                                  stgid=stg_id))[0]
            if rs_dict:
                runpath = rs_dict.get("runpath")
                runstatus = rs_dict.get("status")
                print("runpath", runpath)
                if runstatus == "1":
                    raise Exception("策略已启动，无法再次启动！")
                else:
                    # 运行进程
                    flag = process_stg.start_process(runpath)
                    print("flag########", flag)
                    if flag:
                        # 更新backapproval表
                        tbapp_obj = TBackapproval.objects.using("BackTestDB").get(stgid=stg_id)
                        tbapp_obj.status = "1"
                        tbapp_obj.save()
                        print("stgid#####", stg_id)
                        print("tbapp_obj.status",
                              TBackapproval.objects.using("BackTestDB").values("status").filter(stgid=stg_id))
            else:
                raise Exception("当前策略不存在，无法启动!")
        except Exception as e:
            raise Exception(e)
